<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getLogs, getLogStatistics } from '@/api/index.js'
import { Refresh, Download } from '@element-plus/icons-vue'

// 添加防抖功能
const debounce = (fn, delay) => {
  let timeoutId
  return (...args) => {
    clearTimeout(timeoutId)
    timeoutId = setTimeout(() => fn.apply(null, args), delay)
  }
}

const logs = ref([])
const loading = ref(false)
const statistics = ref({
  total: 0,
  success: 0,
  failed: 0,
  error: 0
})
const pagination = ref({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

const searchForm = ref({
  level: '',
  start_date: '',
  end_date: '',
  keyword: ''
})

const fetchLogs = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.value.currentPage,
      size: pagination.value.pageSize,
      ...searchForm.value
    }
    const res = await getLogs(params)
    if (res.status === 200) {
      logs.value = res.data.results || []
      pagination.value.total = res.data.count || 0
    }
  } catch (error) {
    ElMessage.error('获取日志列表失败')
  } finally {
    loading.value = false
  }
}

const fetchStatistics = async () => {
  try {
    const res = await getLogStatistics()
    if (res.status === 200) {
      statistics.value = res.data
    }
  } catch (error) {
    ElMessage.error('获取统计信息失败')
  }
}

const debouncedSearch = debounce(() => {
  pagination.value.currentPage = 1
  fetchLogs()
}, 500)

const handleSearch = () => {
  pagination.value.currentPage = 1
  fetchLogs()
}

const handleInputSearch = () => {
  debouncedSearch()
}


const handleViewDetail = (row) => {
  ElMessageBox.alert(
    `<div style="text-align: left;">
      <p><strong>时间：</strong>${formatDate(row.timestamp)}</p>
      <p><strong>级别：</strong>${getLevelTag(row.level).text}</p>
      <p><strong>来源：</strong>${row.source}</p>
      <p><strong>用户：</strong>${row.user || '系统'}</p>
      <p><strong>消息：</strong>${row.message}</p>
      ${row.details ? `<p><strong>详细信息：</strong><pre style="background: #f5f5f5; padding: 10px; border-radius: 4px; margin-top: 8px;">${row.details}</pre></p>` : ''}
    </div>`,
    '日志详情',
    {
      confirmButtonText: '关闭',
      dangerouslyUseHTMLString: true,
      customStyle: {
        width: '600px'
      }
    }
  )
}

const handleRefresh = () => {
  fetchLogs()
  fetchStatistics()
}

const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

const formatDate = (dateString) => {
  if (!dateString) return '-'
  try {
    return new Date(dateString).toLocaleString('zh-CN')
  } catch (error) {
    return '-'
  }
}

const getLevelTag = (level) => {
  const levelMap = {
    'INFO': { type: 'success', text: '信息' },
    'WARNING': { type: 'warning', text: '警告' },
    'ERROR': { type: 'danger', text: '错误' },
    'DEBUG': { type: 'info', text: '调试' }
  }
  return levelMap[level] || { type: '', text: level }
}

onMounted(() => {
  fetchLogs()
  fetchStatistics()
})
</script>

<template>
  <div class="log-list">
    <!-- 统计卡片 -->
    <el-row :gutter="20" class="statistics-row">
      <el-col :span="6">
        <el-card>
          <div class="statistic-item">
            <div class="statistic-value">{{ statistics.total }}</div>
            <div class="statistic-label">总日志数</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div class="statistic-item success">
            <div class="statistic-value">{{ statistics.success }}</div>
            <div class="statistic-label">成功</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div class="statistic-item warning">
            <div class="statistic-value">{{ statistics.failed }}</div>
            <div class="statistic-label">失败</div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card>
          <div class="statistic-item danger">
            <div class="statistic-value">{{ statistics.error }}</div>
            <div class="statistic-label">错误</div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <el-card>
      <template #header>
        <div class="card-header">
          <span>日志管理</span>
          <div>
            <el-button :icon="Refresh" @click="handleRefresh">刷新</el-button>
            <el-button :icon="Download" @click="handleExport">导出日志</el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <div class="search-area">
        <el-form :model="searchForm" inline>
          <el-form-item label="日志级别">
            <el-select v-model="searchForm.level" placeholder="请选择日志级别" clearable @change="handleSearch">
              <el-option label="信息" value="INFO" />
              <el-option label="警告" value="WARNING" />
              <el-option label="错误" value="ERROR" />
              <el-option label="调试" value="DEBUG" />
            </el-select>
          </el-form-item>
          <el-form-item label="开始时间">
            <el-date-picker
              v-model="searchForm.start_date"
              type="datetime"
              placeholder="选择开始时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="handleSearch"
            />
          </el-form-item>
          <el-form-item label="结束时间">
            <el-date-picker
              v-model="searchForm.end_date"
              type="datetime"
              placeholder="选择结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
              @change="handleSearch"
            />
          </el-form-item>
          <el-form-item label="关键词">
            <el-input v-model="searchForm.keyword" placeholder="请输入关键词" clearable @input="handleInputSearch" />
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <el-table :data="logs" v-loading="loading" stripe>
        <el-table-column prop="timestamp" label="时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.timestamp) }}
          </template>
        </el-table-column>
        <el-table-column prop="level" label="级别" width="100">
          <template #default="scope">
            <el-tag :type="getLevelTag(scope.row.level).type">
              {{ getLevelTag(scope.row.level).text }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="source" label="来源" width="120" />
        <el-table-column prop="message" label="消息" show-overflow-tooltip />
        <el-table-column prop="user" label="用户" width="100" />
        <el-table-column label="详情" width="100">
          <template #default="scope">
            <el-button size="small" type="primary" @click="handleViewDetail(scope.row)">
              查看详情
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <div class="pagination-area">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[20, 50, 100, 200]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="fetchLogs"
          @current-change="fetchLogs"
        />
      </div>
    </el-card>
  </div>
</template>

<style scoped lang="less">
.log-list {
  .statistics-row {
    margin-bottom: 20px;

    .statistic-item {
      text-align: center;
      
      .statistic-value {
        font-size: 28px;
        font-weight: bold;
        color: #606266;
      }
      
      .statistic-label {
        font-size: 14px;
        color: #909399;
        margin-top: 8px;
      }
      
      &.success .statistic-value {
        color: #67c23a;
      }
      
      &.warning .statistic-value {
        color: #e6a23c;
      }
      
      &.danger .statistic-value {
        color: #f56c6c;
      }
    }
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }

  .search-area {
    margin-bottom: 20px;
    padding: 20px;
    background-color: #f5f7fa;
    border-radius: 4px;
  }

  .pagination-area {
    margin-top: 20px;
    display: flex;
    justify-content: flex-end;
  }
}
</style>